package com.superjson.showpro.dao.impl;

import com.superjson.showpro.base.GenericDaoImpl;
import com.superjson.showpro.dao.ArticleCatalogDao;
import com.superjson.showpro.entity.ArticleCatalog;
import org.hibernate.Query;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class ArticleCatalogDaoImpl extends GenericDaoImpl<ArticleCatalog> implements ArticleCatalogDao {

    public ArticleCatalogDaoImpl() {
        super(ArticleCatalog.class);
    }

    @Override
    public List<ArticleCatalog> listByParent(Long parentId) {
        String sql = "SELECT * FROM sp_article_catalog WHERE is_deleted = 0 AND parent_id = :parentId ORDER BY sort";
        Query query = getSession().createSQLQuery(sql).addEntity(ArticleCatalog.class);
        query.setLong("parentId", parentId);
        return query.list();
    }

    @Override
    public List<ArticleCatalog> list(boolean nullParent) {
        String sql = "SELECT * FROM sp_article_catalog WHERE is_deleted = 0 " +
                (nullParent ? " AND parent_id IS NULL " : " ") +
                " ORDER BY sort";
        Query query = getSession().createSQLQuery(sql).addEntity(ArticleCatalog.class);
        return query.list();
    }

    @Override
    public Integer getMaxSort() {
        String sql = "SELECT IF(MAX(sort) IS NULL,0,MAX(sort)) AS maxSort FROM sp_article_catalog WHERE is_deleted = 0;";
        Query query = getSession().createSQLQuery(sql).addScalar("maxSort", StandardBasicTypes.INTEGER);
        return (Integer) query.uniqueResult();
    }
}

